package com.neu.flashmall.ms.service.impl;

import com.neu.flashmall.ms.entity.SysUser;
import com.neu.flashmall.ms.service.AuthorityCheckService;
import com.neu.flashmall.ms.service.SysMenuService;
import com.neu.flashmall.ms.service.SysRoleMenuService;
import com.neu.flashmall.ms.service.SysUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Set;

@Service
public class AuthorityCheckServiceImpl implements AuthorityCheckService {
    @Resource
    private SysMenuService sysMenuService;

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysRoleMenuService sysRoleMenuService;


    @Override
    public boolean check(String url,String token) throws IOException {
        if(StringUtils.isEmpty(token)) return false;
        SysUser sysUser = sysUserService.getSysUserByTokenWithRedis(token);
        if(sysUser == null) return false;
        Integer roleId = sysUser.getRole();
        HashMap<String, Set<Long>> roleToMenuIdSet = sysRoleMenuService.getRoleToMenuIdSetMap();
        Set<Long> menuIdSet = roleToMenuIdSet.get(String.valueOf(roleId));
        HashMap<String,Long> urlToMenuId = sysMenuService.getUrlToIdMap();
        Long targetMenuId = urlToMenuId.get(url);
        if(targetMenuId == null) return false;
        if(menuIdSet.contains(targetMenuId)) return true;
        return false;
    }


}
